package io.mvvm.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: Netty
 * @description:
 * @author: 潘
 * @create: 2021-04-24 16:27
 **/
@ChannelHandler.Sharable
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    private final static Logger logger = LoggerFactory.getLogger(NettyHttpServerHandler.class);

    /**
     * 读取客户端消息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if (msg instanceof HttpRequest) {
            logger.info("msg 类型 : {}", msg.getClass());
            logger.info("客户端地址 : {}", ctx.channel().remoteAddress());

            // 回复消息给浏览器
            ByteBuf buf = Unpooled.copiedBuffer("Hello Netty Http~", CharsetUtil.UTF_8);

            // 构建Http的响应，即HttpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

            // 写入消息
            ctx.writeAndFlush(response);

        }
    }
}
